import axios from 'axios';
import { message } from 'antd';
require('es6-promise').polyfill();

function getQueryString (url, name) {
  const reg = new RegExp('(^|\\?|&)' + name + '=([^&#]*)(\\s|&|#|$)','i');
  if(reg.test(url)) return RegExp.$2.replace(/\+/g, ' ');
}

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    if (!response.data.success && response.data.code  === 207) {
      message.error(response.data.msg, 3)
      setTimeout(function () {
        location.href = location.origin
      }, 2000)
      return ;
    }
    return response;
  }

  const error = new Error(response.statusText);
  error.response = response;
  throw error;
}

export default async function request(url, options) {
  let response = null;

  if (url) {
    const params = getQueryString(url, 'data');
    if (params) {
      url = url.split('?')[0] + '?data=' + encodeURIComponent(params);
    }
    response = await axios(url);
  } else {
    response = await axios(options)
  }

  checkStatus(response);

  const data = typeof response.data === 'string' ? JSON.parse(response.data) : response.data;
  const ret = {
    data
  };

  return ret;
}
